package com.yao.spider.zhihu.task;

import com.yao.spider.core.httpclient.SimpleRequest;
import com.yao.spider.core.parser.ListPageParser;
import com.yao.spider.core.util.Config;
import com.yao.spider.core.util.Constants;
import com.yao.spider.core.util.HttpClientUtil;
import com.yao.spider.zhihu.Page;
import com.yao.spider.zhihu.ZhiHuHttpClient;
import com.yao.spider.zhihu.dao.IUserDao;
import com.yao.spider.zhihu.dao.Impl.UserDaoImpl;
import com.yao.spider.zhihu.entity.User;
import com.yao.spider.zhihu.parser.ZhiHuUserListPageParser;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.yao.spider.zhihu.ZhiHuHttpClient.parseUserCount;

/**
 * Created by 单耀 on 2017/12/16.
 */
public class DetailListPageTask extends AbstractPageTask{
    private static Logger logger = LoggerFactory.getLogger(DetailListPageTask.class);

    private static ListPageParser proxyUserListPageParser ;

    private IUserDao userDao;

    //TODO 代理
   /* static {
        proxyUserListPageParser = get
    }*/

   /* public static ListPageParser getProxyUserListPageParser() {
        ListPageParser userListPagePageParser = ZhiHuUserListPageParser.getInstance();
//        InvocationHandler invocationHandler = new SimpleIn
    }*/

    public DetailListPageTask(HttpRequestBase request, boolean proxyFlag) {
        super(request, proxyFlag);
    }

    public DetailListPageTask(HttpGet nextRequest, boolean proxyFlag, String userToken) {
        super(nextRequest, proxyFlag, userToken);
    }

    public void handle(Page page) {
        if (!page.getHtml().startsWith("{\"paging\"")) {
            //代理异常，未能正确返回数据丢弃
            logger.error("代理异常，丢弃");
            currentProxy = null;
            return;
        }
        proxyUserListPageParser = new ZhiHuUserListPageParser();
        List<User> list = proxyUserListPageParser.parseListPage(page);
        userDao = new UserDaoImpl();
        for (User user : list) {
            logger.info("解析用户成功：" + user.toString());
            if (Config.dbEnable) {
                try {
//                    System.out.println("11111111111111111111");
                    userDao.insertSelective(user);
                    for (int j = 0; j < user.getFollowees()/20; j++) {
                        if (zhiHuHttpClient.getDetailListPageThreadPool().getQueue().size() > 1000) {
                            continue;
                        }

                        String nextURL = String.format(Constants.USER_FOLLOWEES_URL, user.getUserToken(),j*20);
                        HttpGet nextRequest = new SimpleRequest(user.getUserToken(),nextURL);
//                        HttpGet request = new HttpGet(nextUrl);
                        nextRequest.setHeader("authorization","oauth " + zhiHuHttpClient.getAuthorization());
                        zhiHuHttpClient.getDetailListPageThreadPool().execute(new DetailListPageTask(nextRequest,true, user.getUserToken()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (!Config.dbEnable || zhiHuHttpClient.getDetailListPageThreadPool().getActiveCount() == 1) {
                parseUserCount.incrementAndGet();
                for (int j = 0; j < user.getFollowees() / 20; j++) {
                    String nextUrl = String.format(Constants.USER_FOLLOWEES_URL, user.getUserToken(), j*20);
//                    HttpGet request = new HttpGet(nextUrl);
                    HttpGet request = new SimpleRequest(user.getUserToken(), nextUrl);
                    request.setHeader("authorization", "oauth" + ZhiHuHttpClient.getAuthorization());
                    zhiHuHttpClient.getDetailListPageThreadPool().execute(new DetailListPageTask(request, true, user.getUserToken()));
                }
            }
        }
        System.out.println(page.getHtml());
    }

    public void retry() {
        zhiHuHttpClient.getDetailListPageThreadPool().execute(new DetailListPageTask(request,Config.isProxy));
    }
}
